//
//  OpenListController.swift
//  vmes
//  开工列表页面
//  Created by 志鹏 翟 on 2021/12/29.
//

import Foundation
import UIKit
import Alamofire
import ESPullToRefresh
import EmptyPage

class OpenListController : BaseController,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
    
    class CustomEmptyView: UIView {

        // 标题
        private lazy var tip = UILabel()

        required init?(coder: NSCoder) {
            super.init(coder: coder)
        }

        override init(frame: CGRect) {
            super.init(frame: frame)
            addSubview(tip)
            tip.text="暂无内容"
            tip.snp.makeConstraints { make in
                make.center.equalToSuperview()
            }
        }
    }
    
    var colltionView : UICollectionView?
    var dataArr  = NSMutableArray()//数据源
    
    override func viewWillAppear(_ animated: Bool) {
        navigationController?.navigationBar.tintColor = .black
        navigationController?.setNavigationBarHidden(false, animated: true)
        getData()
      
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        navigationItem.title="开工列表"
        self.view.backgroundColor = .white
        initView()
       
    }
    
    func initView(){
        let height=Int(height) - statusBarHeight
        let layout = UICollectionViewFlowLayout()
        colltionView = UICollectionView(frame: CGRect(x: 0, y: statusBarHeight, width: width, height: height), collectionViewLayout: layout)
        //注册一个cell
        colltionView!.register(MachineCell.self, forCellWithReuseIdentifier:"cell")
        colltionView?.delegate = self;
        colltionView?.dataSource = self;
        //        colltionView?.backgroundColor = UIColor.whiteColor()
        //设置每一个cell的宽高
        layout.itemSize = CGSize(width: (width-60)/3, height: 50)
        layout.sectionInset = UIEdgeInsets.init(top: 10, left: 10, bottom: 10, right: 10)
        self.view.addSubview(colltionView!)
        colltionView?.es.addPullToRefresh {
            [unowned self] in
            getData()
        }
        let customEmptyView = CustomEmptyView()
        colltionView!.ep.set(emptyView: customEmptyView)
        
    }
    
    func getData(){
        spinner.startAnimating()
        let parameters: Dictionary = [
            "pageNum" : "1",
            "pageSize":"99",
            "startoperator":K.userInfo?.userId ?? "",
            "compId":K.userInfo?.company?.companyId ?? "",
            "workshopId": K.currentWorkShop?.workshopId ?? "",
            "workshopType":K.currentWorkShop?.workshopType ?? ""
        ]
        
        sessionManager.request(NetInfo.openList, method:.post
                               , parameters:parameters,encoder: JSONParameterEncoder.default,headers: K.headers!).responseJSON { response in
            self.spinner.stopAnimating()
            self.colltionView!.es.stopPullToRefresh()
            print(response)
            switch response.result {
            case .success:
                if let data=response.data{
                    let response = try? JSONDecoder().decode(MachineList.self, from: data)
                    if(response?.code==200){
                        self.dataArr.removeAllObjects()
                        self.dataArr.addObjects(from: (response?.rows)!)
                        self.colltionView?.reloadData()
                    }else{
                        self.view.makeToast(response?.msg)
                    }
                }
            case .failure:
                print("ERROR")
                self.view.makeToast("请求失败")
            }
        }
       
    }
    
    //返回多少个组
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print(indexPath.item)
        let orderVc = OrderListController()
        orderVc.equidId=(dataArr[indexPath.item] as! MachineItem).id
        orderVc.machineInfo=dataArr[indexPath.item] as! MachineItem
        navigationController?.pushViewController(orderVc, animated: true)
        //        self.present(orderVc, animated: true, completion: nil)
    }
    
    //返回多少个cell
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataArr.count
    }
    
    //返回自定义的cell
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath as IndexPath) as! MachineCell
        cell.roundCorners([.topRight], radius: 15)
        let item = dataArr[indexPath.row] as! MachineItem
        cell.titleLabel?.text = item.equipCode
        cell.titleLabel?.font = .systemFont(ofSize: 15)
        //设置颜色
        if ("G"==item.statusValue) { //生产
            cell.backgroundColor = UIColor.colorWithHex(hexStr: "#67C23A")
        } else if ("Y"==item.statusValue) { //待机
            cell.backgroundColor = UIColor.colorWithHex(hexStr: "#E6A23C")
        } else if ("R"==item.statusValue) {//故障
            cell.backgroundColor = UIColor.colorWithHex(hexStr: "#E63C3C")
        } else {// 关机
            cell.backgroundColor = UIColor.colorWithHex(hexStr: "#999999")
        }
        return cell
    }
    
}
